package com.example.personblog.interceptor;

import com.example.personblog.common.ResultEnum;
import com.example.personblog.exception.BusinessException;
import com.example.personblog.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 如果是 OPTIONS 请求，直接放行
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        String token = request.getHeader("Authorization");
        log.info("Received token: {}", token);

        if (!StringUtils.hasText(token)) {
            log.error("No token found in request");
            throw new BusinessException(ResultEnum.UNAUTHORIZED);
        }

        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        if (!jwtUtil.validateToken(token)) {
            log.error("Invalid token: {}", token);
            throw new BusinessException(ResultEnum.UNAUTHORIZED);
        }

        // 将用户信息存入request
        request.setAttribute("userId", jwtUtil.getUserIdFromToken(token));
        request.setAttribute("username", jwtUtil.getUsernameFromToken(token));

        return true;
    }
}